package com.kc.business.service.impl;


import com.kc.business.domain.KcShareProfitConfig;
import com.kc.business.enums.ShareProfitConfigStatusEnum;
import com.kc.business.enums.ShareProfitTypeEnum;
import com.kc.business.mapper.KcShareProfitConfigMapper;
import com.kc.business.service.KcShareProfitConfigService;
import com.kc.common.constant.Constants;
import com.kc.common.core.domain.AjaxResult;
import com.kc.common.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * FileName: KcShareProfitConfigServiceImpl
 * Author:   TP
 * Date:     2020-11-03 16:29
 * Description: 分润配置表（包含分账、分销配置信息）接口实现
 */
@Service
public class KcShareProfitConfigServiceImpl implements KcShareProfitConfigService {

    @Autowired
    private KcShareProfitConfigMapper shareProfitConfigMapper;

    @Override
    public List<KcShareProfitConfig> getList(KcShareProfitConfig config) {
        config.setIsDeleted(0);
        return shareProfitConfigMapper.select(config);
    }

    @Override
    public KcShareProfitConfig getById(Integer id) {
        if (id != null && id > 0) {
            return shareProfitConfigMapper.selectByPrimaryKey(id);
        }
        return null;
    }

    @Override
    public AjaxResult add(KcShareProfitConfig config) {
        if (config != null) {
            // 各个配置的百分比校验
            AjaxResult ajaxResult = checkPercentConfig(config);
            if (ajaxResult != null) {
                return ajaxResult;
            }
            // 查重
            List<KcShareProfitConfig> configs = shareProfitConfigMapper.getActiveConfigsByNameOrType(
                    config.getProductTypeKey(), config.getProductTypeName());
            if (CollectionUtils.isNotEmpty(configs)) {
                KcShareProfitConfig repetitiveConfig = configs.get(0);
                return AjaxResult.error(String.format("已存在相同%s的分润配置，请勿重复添加",
                        repetitiveConfig.getProductTypeKey().equals(config.getProductTypeKey()) ? "标识" : "名称"));
            }
            if (shareProfitConfigMapper.insertSelective(config) > 0) {
                return AjaxResult.success();
            }
            return AjaxResult.error("操作失败，数据插入失败");
        }
        return AjaxResult.error("操作失败，请指定分润配置信息");
    }

    @Override
    @Transactional
    public AjaxResult update(KcShareProfitConfig config, String loginUserName) {
        if (config != null && config.getId() > 0) {
            // 各个配置的百分比校验
            AjaxResult ajaxResult = checkPercentConfig(config);
            if (ajaxResult != null) {
                return ajaxResult;
            }
            KcShareProfitConfig shareProfitConfig = shareProfitConfigMapper.selectByPrimaryKey(config.getId());
            if (shareProfitConfig == null || Constants.DELETE.equals(shareProfitConfig.getIsDeleted())) {
                return AjaxResult.error("操作失败，未获取到该分润配置信息");
            }
            // 删除原分润配置
            if (shareProfitConfigMapper.deleteById(shareProfitConfig.getId(), loginUserName) > 0) {
                // 新增一个分润配置，版本号+1
                config.setId(null);
                config.setVersion(shareProfitConfig.getVersion() + 1);
                if (shareProfitConfigMapper.insertSelective(config) > 0) {
                    return AjaxResult.success();
                }
            }
            return AjaxResult.error("操作失败，数据库操作失败");
        }
        return AjaxResult.error("操作失败，请指定分润配置信息");
    }


    @Override
    public AjaxResult deleteById(Integer id, String username) {
        if (id != null && id > 0) {
            KcShareProfitConfig shareProfitConfig = shareProfitConfigMapper.selectByPrimaryKey(id);
            if (shareProfitConfig == null || Constants.DELETE.equals(shareProfitConfig.getIsDeleted())) {
                return AjaxResult.success();
            }
            if (shareProfitConfigMapper.deleteById(id, username) > 0) {
                return AjaxResult.success();
            }
            return AjaxResult.success("操作失败，数据库操作失败");
        }
        return AjaxResult.error("操作失败，请指定要删除的分润配置信息");
    }

    @Override
    public AjaxResult audit(KcShareProfitConfig config) {
        if (config != null && config.getId() > 0) {
            KcShareProfitConfig originConfig = shareProfitConfigMapper.selectByPrimaryKey(config.getId());
            if (originConfig == null || Constants.DELETE.equals(originConfig.getIsDeleted())) {
                return AjaxResult.error("操作失败，未找到此分润配置信息");
            }
            if (!ShareProfitConfigStatusEnum.AUDITING.getStatus().equals(originConfig.getAuditStatus())) {
                return AjaxResult.error(String.format("操作失败，此分润配置状态已为[%s]，不能再次审核",
                        ShareProfitConfigStatusEnum.getMessage(config.getAuditStatus())));
            }
            if (ShareProfitConfigStatusEnum.AUDIT_REJECT.getStatus().equals(config.getAuditStatus())) {
                // 审核拒绝
                if (StringUtils.isEmpty(config.getRejectReason())) {
                    return AjaxResult.error("操作失败，审核拒绝必须填写拒绝原因");
                }

            } else if (ShareProfitConfigStatusEnum.AUDIT_SUCCESS.getStatus().equals(config.getAuditStatus())) {
                // 审核通过
                config.setRejectReason(AUDIT_SUCCESS_COMMON_MSG);
            } else {
                return AjaxResult.error("操作失败，请正确指定审批结果");
            }
            if (shareProfitConfigMapper.updateByPrimaryKeySelective(config) > 0) {
                return AjaxResult.success();
            }
            return AjaxResult.error("操作失败，数据库更新失败");
        }
        return AjaxResult.error("操作失败，请指定要审批的分润配置信息");
    }

    @SuppressWarnings("all")
    private AjaxResult checkPercentConfig(KcShareProfitConfig config) {
        Double percentScenic = config.getPercentBillScenic();
        Double percentBillCultureUnion = config.getPercentBillCultureUnion();
        Double percentBillKachuo = config.getPercentBillKachuo();
        Double percentDistributionLevelOne = config.getPercentDistributionLevelOne();
        Double percentDistributionLevelTwo = config.getPercentDistributionLevelTwo();
        if (ShareProfitTypeEnum.SHARE_ALL.getValue().equals(config.getShareProfitType())) {
            if (percentBillCultureUnion < 0 || percentBillCultureUnion > 0.3) {
                return AjaxResult.error("操作失败，文链联盟分账占比配置错误");
            }
            if (percentScenic < 0 || percentScenic > 0.3) {
                return AjaxResult.error("操作失败，景区分账占比配置错误");
            }
            if (percentBillKachuo < 0 || percentBillKachuo > 0.3) {
                return AjaxResult.error("操作失败，卡戳分账占比配置错误");
            }
            if (percentDistributionLevelOne < 0 || percentDistributionLevelOne > 1) {
                return AjaxResult.error("操作失败，一级分销分润占比配置错误");
            }
            if (percentDistributionLevelTwo < 0 || percentDistributionLevelTwo > 1) {
                return AjaxResult.error("操作失败，二级分销分润占比配置错误");
            }
            //分账 + 分销
            BigDecimal total = new BigDecimal(String.valueOf(percentBillCultureUnion))
                    .add(new BigDecimal(String.valueOf(percentBillKachuo)))
                    .add(new BigDecimal(String.valueOf(percentScenic)));
            if (new BigDecimal("0.30").compareTo(total) < 0) {
                return AjaxResult.error("操作失败，分账占比总和不能>0.3");
            }
        } else if (ShareProfitTypeEnum.SHARE_BILL.getValue().equals(config.getShareProfitType())) {
            if (percentBillCultureUnion < 0 || percentBillCultureUnion > 0.3) {
                return AjaxResult.error("操作失败，文链联盟分账占比配置错误");
            }
            if (percentScenic < 0 || percentScenic > 0.3) {
                return AjaxResult.error("操作失败，景区分账占比配置错误");
            }
            if (percentBillKachuo < 0 || percentBillKachuo > 0.3) {
                return AjaxResult.error("操作失败，卡戳分账占比配置错误");
            }
            BigDecimal total = new BigDecimal(String.valueOf(percentBillCultureUnion))
                    .add(new BigDecimal(String.valueOf(percentBillKachuo)))
                    .add(new BigDecimal(String.valueOf(percentScenic)));
            if (new BigDecimal("0.30").compareTo(total) < 0) {
                return AjaxResult.error("操作失败，分账占比总和不能>0.3");
            }
        } else if (ShareProfitTypeEnum.SHARE_DISTRIBUTIONS.getValue().equals(config.getShareProfitType())) {
            // 分销
            if (percentDistributionLevelOne < 0 || percentDistributionLevelOne > 1) {
                return AjaxResult.error("操作失败，一级分销分润占比配置错误");
            }
            if (percentDistributionLevelTwo < 0 || percentDistributionLevelTwo > 1) {
                return AjaxResult.error("操作失败，二级分销分润占比配置错误");
            }
            BigDecimal total = new BigDecimal(String.valueOf(percentDistributionLevelOne))
                    .add(new BigDecimal(String.valueOf(percentDistributionLevelTwo)));
            if (total.compareTo(new BigDecimal("1.00")) > 0) {
                return AjaxResult.error("操作失败，一二级分销占比总和应<1，配置错误");
            }
        } else {
            return AjaxResult.error("请指定正确的分润类型");
        }
        return null;
    }
}
